package com.jswlw.service.biz.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jswlw.common.BaseException;
import com.jswlw.common.ResponseStatus;
import com.jswlw.dao.biz.DistributorAmountRecordMapper;
import com.jswlw.entity.biz.Distributor;
import com.jswlw.entity.biz.DistributorAmountRecord;
import com.jswlw.service.biz.DistributorAmountRecordService;
import com.jswlw.service.biz.DistributorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author 吴维斌 E-mail:wuweibin0817@163.com
 * @version 创建时间：${date} ${time}
 */
@Service
public class DistributorAmountRecordServiceImpl implements DistributorAmountRecordService {

    @Autowired
    DistributorAmountRecordMapper mapper;
    @Autowired
    DistributorService distributorService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(DistributorAmountRecord record) {
        mapper.insertSelective(record);
        Distributor distributor = distributorService.find4Id(record.getDistributorId());
        distributor.setLl(distributor.getLl() + record.getLl());
        distributor.setSc(distributor.getSc() + record.getSc());
        distributorService.update(distributor);

        Distributor distributorParent = distributorService.find4Id(distributor.getParentId());
        if ((distributorParent.getLl() - record.getLl()) < 0) {
            BaseException.sneakyThrows(ResponseStatus.BUSINESS_ERROR.getCode(), "流量不足");
        }
        if ((distributorParent.getSc() - record.getSc()) < 0) {
            BaseException.sneakyThrows(ResponseStatus.BUSINESS_ERROR.getCode(), "时长不足");
        }
        distributorParent.setLl(distributorParent.getLl() - record.getLl());
        distributorParent.setSc(distributorParent.getSc() - record.getSc());
        distributorService.update(distributorParent);
    }

    @Override
    public List<DistributorAmountRecord> queryList(DistributorAmountRecord filter) {
        return mapper.queryList(filter);
    }

    @Override
    public Page<DistributorAmountRecord> queryPage(DistributorAmountRecord filter) {
        PageHelper.startPage(filter.getOffset(), filter.getLimit());
        return (Page<DistributorAmountRecord>) mapper.queryList(filter);
    }
}
